package com.keepalive_kotlin

import android.app.Activity
import android.app.Application
import com.blankj.utilcode.util.Utils
import com.keepalive_kotlin.manager.KeepAliveManager
import com.keepalive_kotlin.utils.BatteryOptimizationUtil

/**
 * 保活工具类
 * 作为保活库的入口类，提供简单的API供外部调用
 */
object KeepAlive {

    private var application: Application? = null

    /**
     * 初始化保活库
     *
     * @param application Application实例
     */
    fun init(application: Application) {
        this.application = application
        // 初始化工具类库
        Utils.init(application)
    }

    /**
     * 获取Application实例
     *
     * @return Application实例
     */
    private fun getApplication(): Application {
        return application ?: throw IllegalStateException("KeepAlive not initialized, please call init() first")
    }

    /**
     * 开始保活服务
     */
    fun startKeepAliveService() {
        KeepAliveManager.getInstance().startKeepAliveService(getApplication())
    }

    /**
     * 停止保活服务
     */
    fun stopKeepAliveService() {
        KeepAliveManager.getInstance().stopKeepAliveService(getApplication())
    }

    /**
     * 检查并请求电池优化白名单
     */
    fun requestBatteryOptimizationWhitelist(activity: Activity) {
        BatteryOptimizationUtil.showBatteryOptimizationDialog(activity, null)
    }

    /**
     * 检查是否已忽略电池优化
     */
    fun isIgnoringBatteryOptimization(): Boolean {
        return BatteryOptimizationUtil.isIgnoringBatteryOptimization(getApplication())
    }

    /**
     * 检查电池优化设置
     */
    fun checkBatteryOptimization(activity: Activity) {
        // 检查是否已忽略电池优化
        if (!KeepAlive.isIgnoringBatteryOptimization()) {
            // 如果没有忽略电池优化，显示提示对话框
            KeepAlive.requestBatteryOptimizationWhitelist(activity)
        }
    }
}